#!/bin/bash

set -e

function fixture() {
  url=$1
  sha=$2
  name=$(basename $url)
  path=examples/$name

  echo $name $path

  if [ ! -d $path ]; then
    git clone --depth=1 $url $path
  fi

  (
    cd $path
    git fetch origin $sha
    git reset --hard $sha
  )
}

fixture https://github.com/FluxML/Flux.jl 3518aa1dd1f0415ed0a13352f2327743f7284c8e # "0.13.9"
fixture https://github.com/GiovineItalia/Gadfly.jl 0bec09d30eca618e10c64fe383024211629c0c65 # 1.3.4
fixture https://github.com/JuliaLang/IJulia.jl 5ad43a3507d3bb427014efd09d8efe19279336e0 # "1.23.3"
fixture https://github.com/fonsp/Pluto.jl 74dfb33d68ac2f6a4ebb5affec019669d154b1a9 # "0.19.18"

all_examples=$(find "examples" -type f -name '*.jl')
known_failures=$(cat script/known-failures.txt)
examples_to_parse=$(
  for example in $all_examples; do
    if [[ ! $known_failures == *$example* ]]; then
      echo $example
    fi
  done
)

echo $examples_to_parse | xargs -n 5000 tree-sitter parse -q -t

skipped=$( echo $known_failures | wc -w )
parsed=$( echo $examples_to_parse | wc -w )
total=$(( parsed + skipped ))
percent=$( bc -l <<< "100*$parsed/$total" )

printf "Successfully parsed %d of %d files (%.2f%%)\n" $parsed $total $percent
